package com.upcoming.container;

import com.alibaba.dubbo.common.utils.ConfigUtils;
import com.alibaba.dubbo.container.Container;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class SpringContainer implements Container {

    private static final Logger logger = LoggerFactory.getLogger(SpringContainer.class);

    private static final String SPRING_CONFIG = "spring.config";

    private static final String DEFAULT_SPRING_CONFIG = "classpath*:conf/*.xml";

    private static ClassPathXmlApplicationContext context;

    public static ClassPathXmlApplicationContext getContext() {
        return context;
    }

    @Override
    public void start() {
        //默认文件加载文件
        String configPath = ConfigUtils.getProperty(SPRING_CONFIG);
        if (configPath == null || configPath.length() == 0) {
            // 从类文件下的conf中读取配置文件
            configPath = DEFAULT_SPRING_CONFIG;
        }

        context = new ClassPathXmlApplicationContext(configPath.split(","));
        context.start();
        String [] names = context.getBeanDefinitionNames();
        for (String name : names) {
            logger.info("容器启动，服务名称：" + name);
        }

    }

    @Override
    public void stop() {
        if (context != null) {
            context.stop();
            context.close();
            context = null;
        }
        logger.info("[事件]容器停止.spring容器已经停止！");
    }
}
